// 仓库推送设置命名空间
var stockpush = {};

// 页面内容定义——开始
stockpush.projectTable = $("#table4StockPush");

// 仓库推送设置的操作对象
stockpush.operation = {};
stockpush.operation.FMLA_SET = "FMLA_SET";
stockpush.operation.SKU_RATIO_SET = "SKU_RATIO_SET";
stockpush.operation.STORAGE_RATIO_SET = "STORAGE_RATIO_SET";

// 仓库推送比例ECharts实例的持有对象
stockpush.storageBarChart = {};
stockpush.finalStorageRatio = {}; // 缓存仓库推送比例相关的相关仓库、店铺、可用店铺、比例等数据，一经初始化不可更改
stockpush.finalSkuRatio = {};// 缓存商品推送比例相关的相关仓库、店铺、可用店铺、比例等数据，一经初始化不可更改

// 统一弹出框定义
var $modal = null;
function showModalDialog(operation) {
    if (operation == stockpush.operation.FMLA_SET) {
        $modal = $("#fmlaModel");
        $modal.find(".modal-title").text("库存公式设置");
        $modal.find("#btnFmlaSave").unbind("click").bind("click", stockpush.saveFmla);
    } else if (operation == stockpush.operation.SKU_RATIO_SET) {
        $modal = $("#skuRatioSetModel").on("shown.bs.modal",function(){
            $("#goodsSkuTable_wrapper",$modal).find(".dataTables_scrollHeadInner,table").css("width","100%");
        });
        
        $modal.find(".modal-title").text("商品推送比例设置");
        $modal.find("#btnSkuRatioSave").unbind("click").bind("click", stockpush.saveSkuRatio);
    } else if (operation == stockpush.operation.STORAGE_RATIO_SET) {
        $modal = $("#storageRatioSetModel");
        $modal.find(".modal-title").text("库存推送比例设置");
        $modal.find("#btnStorageRatioSave").unbind("click").bind("click", stockpush.saveStorageRatio);
    }

    window.top.window.borrowCustomModalDialog($modal).modal("show").one("hidden.bs.modal", function() {
        window.top.window.returnCustomModalDialog();
        stockpush.projectTable.ajax.reload();
    });
};

/*
 * 在DOM上初始化ECharts 传入DOM对象，检测实例是否存在，如果存在就销毁，然后重建对象实例
 */
stockpush.initEchart = function(elementId) {
    var echartInstance = echarts.getInstanceByDom(document.getElementById(elementId));
    if (!!echartInstance && !!echartInstance.dispose) {
        echartInstance.dispose();
    }
    echartInstance = echarts.init(document.getElementById(elementId));
    return echartInstance;
};

stockpush.fmlaClearSet = function(domElement) {

    var projectId = $(domElement).attr("id");
    window.top.window.showModalConfirm("危险，即将删除项目的所有设置", function(event) {
        // 3. 保存数据
        $.ajax({
            type : "GET",
            url : "/stockPush/deleteAllSet.action",
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            data : {
                projectId : projectId
            },
            async : false, // 同步加载表格数据
            success : function(data) {
                if (data.result = "success") {
                    // 提示删除成功，并刷新表格
                    window.top.window.showScoMessage('ok', data.msg);
                    stockpush.projectTable.ajax.reload();
                } else {
                    // 提示删除成功，并刷新表格
                    window.top.window.showScoMessage('error', data.msg);
                }
            },
            error : function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    window.top.window.showModalAlert(result.errorObject.errorText);
                }
            }
        });
    });

}

var destroyTable = function(tableObj) {
    if (!!tableObj && !!tableObj.destroy) {
        tableObj.destroy();
    }
}
// 页面内容定义——结束

// 项目列表页面的初始化
$(document).ready(function() {
    stockpush.initProjectTable();
});

// 初始化项目表格
stockpush.initProjectTable = function() {
    destroyTable(stockpush.projectTable);
    stockpush.projectTable = stockpush.projectTable.DataTable({
        processing : true,
        serverSide : true,
        dom : '<"bottom"rtflp>',
        searching : false,
        pagingType : "full_numbers",
        deferRender : true,
        ajax : {
            traditional : true,
            type : "get",
            url : "/stockPush/getUserProjectWithStockFmla.action"
        },
        tableTools : {
            sRowSelect : "bootstrap"
        },
        columns : [ {
            data : "projectName"
        }, {
            data : "fmlaContent"
        }, {
            className:"text-left",
            data : "stockType",
            render : function(data) {
                var _returnText = "";
                if (data == "ext") {
                    _returnText = "第三方推送";
                } else {
                    _returnText = "本地计算";
                }
                return _returnText;
            }
        }, {
            className:"text-left",
            data : "fmlaRatioStorageContent"
        }
        , {
            data : "fmlaRatioSkuContent",
            "visible" : false
        }, {
            className:"text-left",
            data : "updateTime"
        }, {
            data : "operation"
        } ],
        columnDefs : [ {
            orderable : false,
            targets : [ 0 ]
        }, {
            orderable : false,
            targets : [ 1 ]
        }, {
            orderable : false,
            targets : [ 2 ]
        }, {
            orderable : false,
            targets : [ 3 ]
        }, {
            orderable : false,
            targets : [ 4 ]
        }, {
            orderable : false,
            targets : [ 5 ]
        } ]
    });
};

// -------------------------仓库推送比例数据--开始--------------------
/*
 * 保存仓库推送比例数据
 */

stockpush.saveStorageRatio = function() {
    if (stockpush.isExtend100(stockpush.storageBarChart.getOption())) {
        window.top.window.showModalConfirm("有比例超100%，是否继续", function(event) {
            stockpush.saveStorageRatioData();
        });
    } else {
        stockpush.saveStorageRatioData();
    }
}

stockpush.saveStorageRatioData = function() {
    // 1. 从图表中获取数据
    var dataArray = stockpush.storageBarChart.getOption().series;

    // 2. 构造推送数据params
    // 循环中用到的临时变量 开始
    var currentData = {};
    var currentShop = {};
    var currentStorageData = 0;
    var currentStorage = {};
    // 循环中用到的临时变量 结束
    var params = [];
    var params4Valid = [];

    for (var i = 0, j = dataArray.length; i < j; i++) {
        currentData = dataArray[i];
        currentShop = stockpush.finalStorageRatio.shopArray[i];
        // 如果当前店铺在可设置店铺列表中，才读取各个仓库的比例数据
        if ($.inArray(currentShop.shopId, stockpush.finalStorageRatio.availableShopArray) != -1) {
            for (var u = 0, v = currentData.data.length; u < v; u++) {
                currentStorageData = currentData.data[u];
                currentStorage = stockpush.finalStorageRatio.storageArray[u];
                // 如果推送比例发生了变化，才更新到后台
                if (!!stockpush.finalStorageRatio.storageRatioArray && !!stockpush.finalStorageRatio.storageRatioArray[currentStorage.storId]
                        && !!stockpush.finalStorageRatio.storageRatioArray[currentStorage.storId][currentShop.shopId]) {
                    // 如果历史数据存在，就找出变化了的数据，更新到后台
                    previousStorageData = stockpush.finalStorageRatio.storageRatioArray[currentStorage.storId][currentShop.shopId];
                    var _tempData = {};
                    _tempData.fmlaId = ""; // 库存公式与推送比例不直接关联
                    _tempData.prjId = currentShop.prjId;
                    _tempData.prjName = currentShop.prjName;
                    _tempData.shopId = currentShop.shopId;
                    _tempData.shopName = currentShop.shopName;
                    _tempData.storId = currentStorage.storId;
                    _tempData.storName = currentStorage.storName;
                    _tempData.ratio = currentStorageData;
                    _tempData.isUpdate = 'y';
                    if (currentStorageData != previousStorageData) {
                        params.push(_tempData);
                    }
                    params4Valid.push(_tempData);
                } else {
                    // 如果历史数据不存在，就直接更新到后台
                    var _tempData = {};
                    _tempData.fmlaId = ""; // 库存公式与推送比例不直接关联
                    _tempData.prjId = currentShop.prjId;
                    _tempData.prjName = currentShop.prjName;
                    _tempData.shopId = currentShop.shopId;
                    _tempData.shopName = currentShop.shopName;
                    _tempData.storId = currentStorage.storId;
                    _tempData.storName = currentStorage.storName;
                    _tempData.ratio = currentStorageData;
                    params.push(_tempData);
                    params4Valid.push(_tempData);
                }
            }
        }
    }
    
    var count = 0;
    for(var i=0,j=params4Valid.length;i<j;i++){
        if(Number(params4Valid[i].ratio)==0){
            count++;
        }
    }
    
    //设置仓库库存比例
    if(count==params4Valid.length){
        window.top.window.showModalConfirm("所有推送比例都将设置为0，是否继续", function(event) {
         // 父窗体归还本页的编辑对话框
            window.top.window.returnCustomModalDialog();
         // 3. 保存数据
            var loading = window.top.window.getIndexBusyOverlay();
            $.ajax({
                type : "POST",
                url : "/stockPush/saveStorageRatio.action",
                contentType : "application/json;charset=utf-8",
                dataType : "json",
                data : JSON.stringify(params),
//                async : false, // 同步加载表格数据
                beforeSend:function(){
                    if(loading) {
                    	loading.settext("正在处理中，请稍后...");
                    }
                },
                success : function(data) {
                	loading.remove();
                    // 提示更新成功，并刷新表格
                    window.top.window.showScoMessage('ok', '数据保存成功');
                    $modal.modal('hide');
                },
                error : function(XMLHttpRequest, textStatus) {
                	loading.remove();
                    if (XMLHttpRequest.status == 500) {
                        var result = eval("(" + XMLHttpRequest.responseText + ")");
                        window.top.window.showModalAlert(result.errorObject.errorText);
                    }
                }
            });
        });
    }else{
     // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
     // 3. 保存数据
        var loading = window.top.window.getIndexBusyOverlay();
        $.ajax({
            type : "POST",
            url : "/stockPush/saveStorageRatio.action",
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            data : JSON.stringify(params),
//            async : false, // 同步加载表格数据
            beforeSend:function(){
                if(loading) {
                	loading.settext("正在处理中，请稍后...");
                }
            },
            success : function(data) {
            	loading.remove();
                // 提示更新成功，并刷新表格
                window.top.window.showScoMessage('ok', '数据保存成功');
                $modal.modal('hide');
            },
            error : function(XMLHttpRequest, textStatus) {
            	loading.remove();
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    window.top.window.showModalAlert(result.errorObject.errorText);
                }
            }
        });
    };
};

stockpush.storageBarChartInitOption = {
    tooltip : {
        trigger : 'axis',
        axisPointer : { // 坐标轴指示器,坐标轴触发有效
            type : 'shadow' // 默认为直线,可选为：'line' | 'shadow'
        }
    },
    legend : {
        data : [],
        orient : 'vertical',
        x : 'right',
        width : 150,
        top : 50,
        right : 20
    },
    grid : {
        left : '2%',
        right : '170',
        bottom : '10%',
        containLabel : true
    },
    yAxis : {
        type : 'value',
        data : []
    },
    // 仓库太多时放开，提供横向滚动功能
//    dataZoom: {
//        show: true,
//        realtime: true,
//        y: 36,
//        height: 20,
//        start: 0,
//        end: 80
//    },
    xAxis : {
        type : 'category',
        data : [],
        triggerEvent : true,
        axisLabel:{
            show:true,
            interval:0,
            margin:2,
            formatter:function(params){
                return formatLabel(params);
            }
        }
    },
    series : [

    ]
};

var formatLabel = function(params){
    var newParamsName = "";// 最终拼接成的字符串
    var paramsNameNumber = params.length;// 实际标签的个数
    var provideNumber = 5;// 每行能显示的字的个数
    var rowNumber = Math.ceil(paramsNameNumber / provideNumber);// 换行的话，需要显示几行，向上取整
    /**
     * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
     */
    // 条件等同于rowNumber>1
    if (paramsNameNumber > provideNumber) {
        /** 循环每一行,p表示行 */
        for (var p = 0; p < rowNumber; p++) {
            var tempStr = "";// 表示每一次截取的字符串
            var start = p * provideNumber;// 开始截取的位置
            var end = start + provideNumber;// 结束截取的位置
            // 此处特殊处理最后一行的索引值
            if (p == rowNumber - 1) {
                // 最后一次不换行
                tempStr = params.substring(start, paramsNameNumber);
            } else {
                // 每一次拼接字符串并换行
                tempStr = params.substring(start, end) + "\n";
            }
            newParamsName += tempStr;// 最终拼成的字符串
        }

    } else {
        // 将旧标签的值赋给新标签
        newParamsName = params;
    }
    // 将最终的字符串返回
    return newParamsName;
}

// 初始化仓库推送比例
stockpush.initEchart4Storage = function() {
    // 初始化一个空的表格
    stockpush.storageBarChart = stockpush.initEchart("storageChart");
    // 根据初始化参数绘制图表
    stockpush.storageBarChart.setOption(stockpush.storageBarChartInitOption);
    // 绑定图表的点击事件
    stockpush.storageBarChart.on("click", function(params) {
        stockpush.initOptionData4Chart(params);
    });
};

// 点击"库存推送比例设置"按钮的调用方法
stockpush.fmlaRatioStockSet = function(domElement) {
    var projectId = $(domElement).attr("id");

    // 初始化图表，缓存到stockpush.storageBarChart上
    stockpush.initEchart4Storage();

    // 向服务器请求仓库推送比例数据，并初始化显示结果
    stockpush.queryStockPushData(projectId);
};

// 向服务器请求仓库推送比例数据，并初始化显示结果
stockpush.queryStockPushData = function(projectId) {
    $.ajax({
        type : "GET",
        url : "/stockPush/getStorageRatio.action",
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        data : {
            projectId : projectId
        },
        async : false, // 同步加载表格数据
        success : function(data) {
            // 将仓库推送比例相关数据缓存起来,因为页面上其它控件在计算时会用到
            stockpush.finalStorageRatio = data;
            if (data.result == "success") {
                
                stockpush.initRatioStoragePage(stockpush.storageBarChartInitOption);
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

var getStoreIndexByName = function(storList, storName) {
    var returnIndex = 0;
    for (var i = 0, j = storList.length; i < j; i++) {
        if (storList[i].storName == storName) {
            returnIndex = i;
            break;
        }
    }
    return returnIndex;
};

/*
 * 点击图表时执行的方法
 */
stockpush.initOptionData4Chart = function(params) {

    var currentName = params.name || params.value;
    var storList = stockpush.finalStorageRatio.storageArray;
    var currentIndex = params.dataIndex || getStoreIndexByName(storList, params.value);
    // 设置表单的title部分
    $("#storageName", $modal).html(currentName).val(currentIndex);
    
    stockpush.initRatioInputAreaByStorIndex(currentIndex, $modal);
};

// 清空图表option和库存推送页面的数据
stockpush.cleanRatioStoragePage = function(option) {
    // 清空图表中的数据项
    option.xAxis.data.length = 0;
    option.legend.data.length = 0;
    option.series.length = 0;
    $("#shopInputContainer").empty().hide();
};

// 根据店铺ID获取店铺在各个仓库上的比例,如果设置过，就添加数据，如果没有设置过，就添加0；
stockpush.getShopRatio = function(shopId) {
    var returnData = [];
    var storageArray = stockpush.finalStorageRatio.storageArray;
    var storageRatioArray = stockpush.finalStorageRatio.storageRatioArray;
    for (var i = 0, j = storageArray.length; i < j; i++) {
        var storage = storageArray[i];
        if (!!storageRatioArray[storage.storId]) {
            returnData[i] = storageRatioArray[storage.storId][shopId] || 0;
        } else {
            returnData[i] = 0;
        }
    }

    return returnData;
};

// 初始化图表的店铺图例
stockpush.initStorageBarChartYSeries = function(shopArray, option) {
    for (var i = 0, j = shopArray.length; i < j; i++) {
        var shopObj = shopArray[i];
        var ratioData = stockpush.getShopRatio(shopObj.shopId);
        var itemValue = {
            name : shopObj.shopName,
            type : 'bar',
            stack : '百分比',
            label : {
                normal : {
                    show : true,
                    position : 'insideRight'
                }
            },
            data : ratioData,
            markLine : {
                lineStyle : {
                    emphasis : {
                        color : "#e74c3c",
                        type : "solid"
                    }
                },
                silent : true,
                data : [ {
                    yAxis : '100'
                } ]
            }
        }
        // 1. 初始化图例
        option.legend.data.push(shopObj.shopName);
        // 2. 初始化图表数据
        option.series.push(itemValue);
    }
};

// 初始化店铺input区域
stockpush.initShopInputContainer = function(shopArray) {

    var curStorageIndex = $("#storageName").val();

    var availableShopArray = stockpush.finalStorageRatio.availableShopArray;
    var rowLength = 3;
    var tempHtml = "";
    var inputDisabled = "disabled";

    for (var i = 0, j = shopArray.length; i < j; i++) {
        var shopObj = shopArray[i];
        var storageRatio = stockpush.getShopRatio(shopObj.shopId);
        // 设置是否可编辑
        inputDisabled = "disabled";

        if ($.inArray(shopObj.shopId, availableShopArray) != -1) {
            inputDisabled = "";
        }

        if (i % rowLength == 0) {
            // 一行开始，添加行开始
            tempHtml = "<div class='row'>";
        }

        tempHtml += "<div class='col-sm-2 text-right'><label class='control-label'>" + shopObj.shopName
                + "</label></div><div class='col-sm-2'><span class='input-group'><input " + inputDisabled + " class='form-control text-right' type='text' id="
                + shopObj.shopId + " placeholder='%' name='" + i + "'/><span class='input-group-addon' style='padding:1px!important;'>%</span></span></div>";

        // 一行开始结尾或者控件列表结尾，添加行结尾
        if (i % rowLength == (rowLength - 1) || i == j - 1) {
            tempHtml += "</div>";
            $("#shopInputContainer").append($(tempHtml));
        }
    };

    // 设置店铺推送比例输入框的change事件，使修改比例后图表联动
    $("#shopInputContainer").find("input[type='text']").inputmask({
    	mask : "999",
        greedy : false,
        placeholder : '',
//        regex : "^(\\d|[1-9]\\d|100)$"
    }).bind("change", function(e) { // 当数据变化时，同步更新图表中的显示内容
        var index = $(this).attr("name"); // 获取当前店铺input在列表中的index
        var value = $(this).val();
        var option = stockpush.storageBarChart.getOption();
        var storageIndex = $("#storageName", $modal).val();
        option.series[index].data[storageIndex] = value;
        stockpush.storageBarChart.setOption(option);
    });
    $("#shopInputContainer").find("input[type='text']").keyup(function(){
    	var tem = $(this).val();
    	if(parseInt(tem)>100){
    		var str = tem.substr(0,tem.length-1);
    		$(this).val("100");
    		$(this).change();
    	}
    })
};

stockpush.getRatioDataFromChart = function(chart, storIndex, ShopIndex) {
    var _value = chart.getOption().series[ShopIndex].data[storIndex];
    return _value||0;
}

/*
 * 将input中的数据设置为显示第n个仓库的数据
 */
stockpush.initRatioInputAreaByStorIndex = function(index, context) {
    var data = stockpush.finalStorageRatio;
    
    var context = context || undefined;
    $("#storageName", context).html(data.storageArray[index].name).val(index);

    // 获取当前仓库可访问的店铺列表
    var storeAvalilableShopList = stockpush.getShopStoreRelation(data.storageArray[index].storId, data.shopStorRelationArray);
    if (storeAvalilableShopList.length > 0) {
        $("#shopInputContainer", context).find("input").each(
                function(i, element) {
                    
                    var _value = "0";
                    // 如果店铺不可以访问仓库，则设置不可用并保留diabled
                    if ($.inArray($(element).attr("id"), storeAvalilableShopList) == -1) {
                        $(element).val("").attr("placeholder","0.00").attr("disabled", true);
                        $(element).parents("div").eq(0).hide();
                        $(element).parents("div").eq(0).prev().hide();
                    } else if ($.inArray($(element).attr("id"), storeAvalilableShopList) != -1
                            && $.inArray($(element).attr("id"), data.availableShopArray) == -1) {
                        // 如果店铺可以访问仓库，并且当前登录人不可以设置店铺，则设置取值，保留disabled
                        _value = stockpush.getRatioDataFromChart(stockpush.storageBarChart, index, i);
                        if(_value != 0){
                        	var attr = _value.split(".");
                            element.value = attr[0];
                        }else
                        element.value = _value;
                        $(element).parents("div").eq(0).show();
                        $(element).parents("div").eq(0).prev().show();
                    } else {
                        // 如果店铺可以访问仓库，并且当前登录人可以设置店铺，则设置取值，并且取消disabled
                        $(element).removeAttr("disabled");
                        _value = stockpush.getRatioDataFromChart(stockpush.storageBarChart, index, i);
                        if(_value != 0){
                        	var attr = _value.split(".");
                            element.value = attr[0];
                        }else
                        element.value = _value;
                        $(element).parents("div").eq(0).show();
                        $(element).parents("div").eq(0).prev().show();
                    }
                });
    }
    
};

/*
 * 初始化仓库店铺推送比例设置页面： 1. 初始化ECharts图表 2. 初始化店铺比例设置控件列表
 */
stockpush.initRatioStoragePage = function(option) {
    var data = stockpush.finalStorageRatio;
    var option = option || stockpush.storageBarChart.getOption();

    stockpush.cleanRatioStoragePage(option);
    if (!data.storageArray || data.storageArray.length == 0) {
        // 如果仓库数据不存在，则给出提示
        window.top.window.showScoMessage('error', "该项目下的店铺没有仓库");
    } else if (!data.shopArray || data.shopArray.length == 0) {
        window.top.window.showScoMessage('error', "该项目下没店铺");
    } else {
        // 为option设置横坐标为仓库列表
        for (var i = 0, j = data.storageArray.length; i < j; i++) {
            option.xAxis.data.push(data.storageArray[i].name);
        }
        // 为option设置店铺图例为店铺列表
        stockpush.initStorageBarChartYSeries(data.shopArray, option);
        stockpush.storageBarChart.setOption(option);

        // 显示店铺列表的比例数据，每行三条
        stockpush.initShopInputContainer(data.shopArray);
        $("#shopInputContainer").show();

        // 将input内容设置为第1个仓库的数据
        stockpush.initRatioInputAreaByStorIndex(0);
        
        // 显示弹出框
        showModalDialog(stockpush.operation.STORAGE_RATIO_SET);
    }

};
// -------------------------仓库推送比例数据--结束--------------------

// -------------------------项目库存公式--开始--------------------
stockpush.initFmlaPage = function(prjId, data) {
    $(".icheck").iCheck({
        checkboxClass : 'icheckbox_flat-red',
        radioClass : 'iradio_flat-red'
    });
    $("#expression", $modal).attr("readonly", "true");
    $("#expression", $modal).maxlength({
        alwaysShow : false,
        threshold : 20,
        warningClass : "label label-warning",
        limitReachedClass : "label label-danger",
        separator : ' / '
    });
    // 绑定页面上的参数按钮点击事件
    $(".btnFmlaElement", $modal).unbind("click").bind("click", function() {
        var originExpression = $("#expression", $modal).val();
        var expression = originExpression += "{{" + $(this).text() + "}}";
        $("#expression", $modal).val(expression);
        stockpush.initBtnDisableState($modal);
    });

    // 绑定页面上的操作符按钮点击事件
    $(".btnFmlaSign", $modal).unbind("click").bind("click", function() {
        var originExpression = $("#expression", $modal).val();
        var expression = originExpression += " " + $(this).text() + " ";
        $("#expression", $modal).val(expression);
    });

    // 绑定页面上的公式校验操作符按钮点击事件
    $("#btnFmlaValid", $modal).unbind("click").bind("click", function() {
        var testExpression = $("#expression", $modal).val();
        stockpush.fmlaSetValid(testExpression, true);
    });

    // 绑定页面上清空按钮点击事件
    $("#btnFmlaClear", $modal).unbind("click").bind("click", function() {
        $("#expression", $modal).val("");
        stockpush.initBtnDisableState($modal);
    });

    // 绑定页面上退格按钮点击事件，遇到参数时，参数将整体删除
    $("#sliceBtn", $modal).unbind("click").bind("click", function() {
        var originExpression = $.trim($("#expression", $modal).val());
        var expression = originExpression;
        if (originExpression.charAt(originExpression.length - 1) == "}") {
            var startIndex = originExpression.lastIndexOf("{{");
            expression = originExpression.substring(0, startIndex);
        } else {
            expression = originExpression.substring(0, originExpression.length - 1);
        }
        $("#expression", $modal).val(expression);
        stockpush.initBtnDisableState($modal);
    });

    if (!!data) {
        $("#expression", $modal).val(data.formula);
        $("#prjId", $modal).val(data.prjId);
        $("#prjName", $modal).val(data.prjName);
        $("#fmlaId", $modal).val(data.fmlaId);
        $("#" + data.stockValMode, $modal).iCheck("check");
        if ("y" == data.isVirtualCount) {
            $("#isVirtualCount", $modal).iCheck("check");
        } else {
            $("#isVirtualCount", $modal).iCheck("uncheck");
        }
        if ("y" == data.isSubUnPaid) {
            $("#isSubUnPaid", $modal).iCheck("check");
        } else {
            $("#isSubUnPaid", $modal).iCheck("uncheck");
        }
    } else {
        $("#expression", $modal).val("");
        $("#prjId", $modal).val(prjId);
        $("#prjName", $modal).val("");
        $("#fmlaId", $modal).val("");
        $("#local", $modal).iCheck("uncheck");
        $("#ext", $modal).iCheck("uncheck");
        $("#isVirtualCount", $modal).iCheck("uncheck");
        $("#isSubUnPaid", $modal).iCheck("uncheck");
    }

    stockpush.initBtnDisableState();
};

stockpush.saveFmla = function() {

    // 父窗体归还本页的编辑对话框
    // 校验规则
    var expression = $("#expression", $modal).val();
    
    var stockValMode = $("input[name='storageResourceType']:checked",$modal).attr("id");
    
    if(!stockValMode){
        window.top.window.showScoMessage('error', "请选择库存来源");
        return;
    }
    if (stockpush.fmlaSetValid(expression, false)) {
        window.top.window.returnCustomModalDialog();
        // 构造数据
        var params = {};
        params.fmlaId = $("#fmlaId", $modal).val();
        params.prjId = $("#prjId", $modal).val();
        params.prjName = $("#prjName", $modal).val();
        params.formula = $("#expression", $modal).val();
        params.ratioSetMode = "sku";
        params.isVirtualCount = $("#isVirtualCount").is(":checked") ? "y" : "n";
        params.stockValMode = $("input[name='storageResourceType']:checked").attr("id"); // local
        params.isSubUnPaid = $("#isSubUnPaid").is(":checked") ? "y" : "n"; // 是否扣减未付款数
        // or
        // ext

        // 保存库存公式
        var loading = window.top.window.getIndexBusyOverlay();
        $.ajax({
            type : "POST",
            url : "/stockPush/saveStorageFmla.action",
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            data : JSON.stringify(params),
//            async : false,
            beforeSend:function(){
                if(loading) {
                	loading.settext("正在处理中，请稍后...");
                }
            },
            success : function(data) {
            	loading.remove();
                if (data.result = "success") {
                    // 提示更新成功，并刷新表格
                    window.top.window.showScoMessage('ok', data.msg);
                    $modal.modal('hide');
                } else {
                    window.top.window.showScoMessage('error', data.msg);
                }
            },
            error : function(XMLHttpRequest, textStatus) {
            	loading.remove();
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    window.top.window.showModalAlert(result.errorObject.errorText);
                }
            }
        });
    }
};
// 校验库存公式是否有效
stockpush.fmlaSetValid = function(expression, isShowOkMessage) {
    var validResult = true;
    var exp = /\{\{[^}]*\}\}/g;
    var testExpression = expression.replace(exp, function() {
        return parseInt(100 * Math.random())
    });
    try {
        if (expression.indexOf("}} {{") > 0 || expression.indexOf("}}{{") > 0) {
            validResult = false;
        } else {
            if (checkCorrect(testExpression)) {
                var testResult = eval(testExpression.replace(/\s/g, ""));
                // 下面语句用于判断testResult是否为数字类型
                if (!testResult === +testResult) {
                    validResult = false;
                }
            } else {
                validResult = false;
            }
        }
    } catch (e) {
        validResult = false;
    } finally {
        if (!validResult) {
            window.top.window.showScoMessage('error', "库存公式校验失败");
        } else {
            if (!!isShowOkMessage) {
                window.top.window.showScoMessage('ok', "库存公式校验成功");
            }
        }
    }
    return validResult;
};
// 库存公式设置-点击库存公式按钮时调用此方法
stockpush.fmlaSet = function(domElement) {
    // 获取当前项目ID
    var projectId = $(domElement).attr("id");

    // 根据项目ID获取项目公式，并填充到页面中
    $.ajax({
        type : "get",
        url : "/stockPush/getStorageFmla.action",
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        data : {
            projectId : projectId
        },
        async : false, // 同步加载表格数据
        success : function(data) {
            stockpush.initFmlaPage(projectId, data.stockFmla); // 初始化项目设置页面
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });

    // 弹出库存公式设置页面
    showModalDialog(stockpush.operation.FMLA_SET);
};
// -------------------------项目库存公式--结束--------------------

// -------------------------商品推送比例--开始--------------------
stockpush.goodsSkuTable = null;
stockpush.projectId = "";
/*
 * 初始化商品表格，默认查询所有商品
 */
stockpush.initGoodsSkuTable = function(projectId) {
    $("#quickSearch").val("");
    
    if (!projectId) {
        projectId = stockpush.projectId;
    }
    
    if (!$.fn.DataTable.isDataTable('#goodsSkuTable')) {
    stockpush.goodsSkuTable = $("#goodsSkuTable")
            .DataTable(
                    {
                        processing : true,
                        deferLoading:0,
                        serverSide : true,
                        dom : '<"bottom"rtflp>',
                        searching : false,
                        paging : false,
                        autoWidth:false,
                        scrollY : "200px",
                        scrollCollapse : false,
                        pagingType : "full_numbers",
                        deferRender : true,
                        select : {
                            items : 'row'
                        },
                        ajax : {
                            traditional : true,
                            type : "get",
                            url : "/stockPush/getSkuRatioList.action",
                            data : {
                                quickSearch : encodeURI($("#quickSearch").val()),
                                isSet : $("#isSet").val(),
                                projectId : projectId
                            }
                        },
                        tableTools : {
                            sRowSelect : "bootstrap"
                        },
                        "columns" : [
                                {
                                    "data" : "operation",
                                    "defaultContent" : "<a href='javascript:void(0)' class='delete-btn' title='不设置此行' type='button'><i class='fa fa-trash-o'></i></a>&nbsp;&nbsp;<a href='javascript:void(0)' disabled class='remove-set-btn' title='清除该商品的设置' type='button'><i class='fa fa-eraser'></i></a>",
                                    "orderable" : false,
                                    "class" : "text-center"
                                }, {
                                    "data" : "goodsCode",
                                    "orderable" : false
                                }, {
                                    "data" : "goodsName",
                                    "orderable" : false
                                }, {
                                    "data" : "skuCode",
                                    "orderable" : false
                                }, {
                                    "data" : "skuName",
                                    "orderable" : false
                                }, {
                                    "data" : "isSet",
                                    render : function(data) {
                                        var _returnValue = "";
                                        if (data == "set") {
                                            _returnValue = "已设置";
                                        } else if (data == "unset") {
                                            _returnValue = "未设置";
                                        }
                                        return _returnValue;
                                    }
                                }, {
                                    "data" : "skuId",
                                    "orderable" : false,
                                    "visible" : false
                                }, {
                                    "data" : "goodsId",
                                    "orderable" : false,
                                    "visible" : false
                                } ]
                    }).on('draw.dt', function() {
                stockpush.initTableRowEvent($modal);
            });
    }else{
        stockpush.goodsSkuTable.clear().draw();
    }
};

stockpush.initBtnDisableState = function(context) {
    if (!context) {
        context = window.document;
    }
    var textValue = $("#expression", context).val();

    $(".btnFmlaElement", context).each(function() {
        var text = $(this).text();
        if (textValue.indexOf(text) > 0) {
            $(this).attr("disabled", true);
        } else {
            $(this).attr("disabled", false);
        }
    });
}

// 初始化表格的行控件事件
stockpush.initTableRowEvent = function(context) {
    $("#goodsSkuTable tbody .delete-btn", context).on("click", function(event) {
        var row = stockpush.goodsSkuTable.row($(this).parents("tr").eq(0));
        row.remove();
        $(this).parents("tr").eq(0).remove();

        event.stopPropagation(); // 防止冒泡
    });

    $("#goodsSkuTable tbody .remove-set-btn", context).on("click", function(event) {

        var row = stockpush.goodsSkuTable.row($(this).parents("tr").eq(0));
        var rowData = row.data();
        var skuId = rowData.skuId;
        var prjId = rowData.prjId;
        window.top.window.showModalConfirm("确定要删除该商品的设置吗？", function(event) {
            stockpush.removeSkuRatio(prjId, skuId);
        });
        event.stopPropagation(); // 防止冒泡
    });

    $("#goodsSkuTable tbody td", context).on("click", function(event) {
        
        // 设置行的选中状态
        $(this).parents("tr").eq(0).toggleClass("selected");
        $(this).parents("tr").eq(0).siblings().removeClass("selected");

        // 获取选中行的相关数据，加载推送比例数据
        var row = stockpush.goodsSkuTable.row($(this).parents("tr"));
        var rowData = row.data();
        stockpush.loadSingleSkuRatio(rowData, context);
        event.stopPropagation(); // 防止冒泡
    });
};

stockpush.removeSkuRatio = function(prjId, skuId) {
    $.ajax({
        type : "GET",
        url : "/stockPush/deleteSkuRatioBySkuId.action",
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        data : {
            projectId : prjId,
            skuId : skuId
        },
        async : false, // 同步加载表格数据
        success : function(data) {
            if (data.result == "success") {
                // 表格重新加载
                window.top.window.showScoMessage('ok', '删除成功');
                stockpush.reloadGoodsSkuTable();
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });

};

/*
 * 当选中一条商品时，显示该条商品的库存推送比例设置
 */
stockpush.loadSingleSkuRatio = function(rowData, context) {
    var projectId = rowData.prjId;
    var skuId = rowData.skuId;
    var isSet = rowData.isSet;

    $("#shopInputContainer4Sku", context).find("input").val("0"); // 清空input框
    $("#SkuName", context).text(rowData.goodsName + "-" + rowData.skuName);

    if (isSet == "unset") {
        // 如果未设置，则默认显示仓库推送比例
        stockpush.initRatioSkuPage(stockpush.initSkuStorageBarChartOption);
        stockpush.initRatioInputAreaByStorIndex_sku(0, $modal);
    } else {
        // 如果设置过，就请求数据并加载
        // 获取商品的库存推送比例
        stockpush.skuStorageBarChart.showLoading();
        $.ajax({
            type : "GET",
            url : "/stockPush/getSkuRatioBySkuId.action",
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            data : {
                projectId : projectId,
                skuId : skuId
            },
            async : false, // 同步加载表格数据
            success : function(data) {
                if (data.result == "success") {
                    stockpush.initRatioSkuChartWithData(data.skuRatioArray, skuId);
                    stockpush.skuStorageBarChart.hideLoading();
                } else {
                    window.top.window.showModalAlert(data.msg);
                }
            },
            error : function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    window.top.window.showModalAlert(result.errorObject.errorText);
                }
            }
        });
    }
};

// 图表单击事件绑定
stockpush.barClickCallback = function(params, context) {
    var currentName = params.name || params.value;
    var storList = stockpush.finalSkuRatio.storageArray;
    var currentIndex = params.dataIndex || getStoreIndexByName(storList, params.value);
    var context = context || undefined;
    // 设置表单的title部分
    $("#storageName4Sku", context).html(currentName).val(currentIndex);
    stockpush.initRatioInputAreaByStorIndex_sku(currentIndex, context);
};

// 根据图表上的仓库index设置input数据
stockpush.initRatioInputAreaByStorIndex_sku = function(storIndex, context) {
    var data = stockpush.finalSkuRatio;
    var storeAvalilableShopList = stockpush.getShopStoreRelation(data.storageArray[storIndex].storId, data.shopStorRelationArray);
    if (!!storeAvalilableShopList && storeAvalilableShopList.length <= 0) {
        window.top.window.showModalAlert("仓库没有关联的店铺");
    } else {
        $("#shopInputContainer4Sku", context).find("input").each(
                function(index, element) {
                    
                    // 如果店铺不可以访问仓库，则设置不可用并保留diabled
                    if ($.inArray($(element).attr("id"), storeAvalilableShopList) == -1) {
                        $(element).val("").attr("placeholder", "0.00").attr("disabled", true);
                        $(element).parents("div").eq(0).hide();
                        $(element).parents("div").eq(0).prev().hide();
                    } else if ($.inArray($(element).attr("id"), storeAvalilableShopList) != -1
                            && $.inArray($(element).attr("id"), data.availableShopArray) == -1) {
                        // 如果店铺可以访问仓库，并且当前登录人不可以设置店铺，则设置取值，保留disabled
                        var _value = stockpush.getRatioDataFromChart(stockpush.skuStorageBarChart, storIndex, index);
                        $(element).val(_value);
                        $(element).parents("div").eq(0).show();
                        $(element).parents("div").eq(0).prev().show();
                    } else {
                        // 如果店铺可以访问仓库，并且当前登录人可以设置店铺，则设置取值，并且取消disabled
                        $(element).removeAttr("disabled");
                        var _value = stockpush.getRatioDataFromChart(stockpush.skuStorageBarChart, storIndex, index);
                        $(element).val(_value);
                        $(element).parents("div").eq(0).show();
                        $(element).parents("div").eq(0).prev().show();
                    }
                });
        $("#storageName4Sku", context).html(data.storageArray[storIndex].storName).val(storIndex);
    }
};

stockpush.initSkuStorageBarChartOption = {
    tooltip : {
        trigger : 'axis',
        axisPointer : { // 坐标轴指示器,坐标轴触发有效
            type : 'shadow' // 默认为直线,可选为：'line' | 'shadow'
        }
    },
    legend : {
        data : [],
        orient : 'vertical',
        x : 'right',
        width : '15%',
        right : '0%'
    },
    grid : {
        left : '2%',
        right : '25%',
        bottom : '3%',
        top : '10%',
        containLabel : true
    },
    yAxis : {
        type : 'value'
    },
    xAxis : {
        type : 'category',
        data : [],
        triggerEvent : true,
        axisLabel:{
            show:true,
            interval:0,
            formatter:function(params){
                return formatLabel(params);
            }
        }
    },
    series : [

    ]
};

stockpush.initSkuStorageBarChart = function() {
    stockpush.skuStorageBarChart.setOption(stockpush.initSkuStorageBarChartOption);
};

stockpush.initSkuStorageBarChartWithData = function(projectId) {
    $.ajax({
        type : "GET",
        url : "/stockPush/getStorageRatio.action",
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        data : {
            projectId : projectId
        },
        async : false, // 同步加载表格数据
        success : function(data) {
            // 将仓库推送比例相关数据缓存起来,在商品推送比例页上初始化时，显示仓库推送比例
            stockpush.finalSkuRatio = data;
            if (data.result == "success") {
                // 根据获取到的数据初始化页面
                stockpush.initRatioSkuPage(stockpush.initSkuStorageBarChartOption);
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

/*
 * 商品推送比例设置按钮的点击事件
 */
stockpush.fmlaRatioSkuSet = function(domElement) {
    var projectId = $(domElement).attr("id");
    stockpush.projectId = projectId;
    stockpush.skuStorageBarChart = stockpush.initEchart("skuStorageChart"); // 初始化空的图表控件
    stockpush.initGoodsSkuTable(projectId); // 初始化商品列表
    $("#btnGoodsSkuSearch").unbind("click").bind("click", stockpush.reloadGoodsSkuTable); // 初始化查询按钮

    // 图表点击事件，将图表中的数据绑定到数据展示列表中
    stockpush.skuStorageBarChart.on("click", function(params) {
        stockpush.barClickCallback(params, $modal);
    });

    // 根据初始化参数初始化图表控件
    stockpush.initSkuStorageBarChart();

    // 初始化批量设置按钮
    $("#btnSkuRatioMultiSet").unbind("click").bind("click", function() {
        stockpush.setRowSelected($modal);
    });
    // 获取仓库推送比例数据，并初始化显示结果
    stockpush.initSkuStorageBarChartWithData(projectId);

};

// 批量选中
stockpush.setRowSelected = function(context) {
    
    $("#goodsSkuTable", context).find("tbody>tr").addClass("selected");
    stockpush.initRatioSkuPage(stockpush.initSkuStorageBarChartOption); // 批量设置时，显示为仓库推送比例
    $("#SkuName", context).text("选中商品批量设置");
}

stockpush.finalSkuRatio4Single = {};

/*
 * 根据data和sku设置图表内容和控件内容： data：{storId:[{shopId:radio},{shopId:radio},...]}
 * skuId:商品规格ID
 */

stockpush.initRatioSkuChartWithData = function(data, skuId) {
    if (!!skuId) {
        // 缓存逐条的商品规格
        stockpush.finalSkuRatio4Single[skuId] = data;
    }

    var option = stockpush.skuStorageBarChart.getOption();

    // 初始化y轴的数据
    var shopArray = stockpush.finalSkuRatio.shopArray;

    var seriesList = option.series;

    for (var i = 0, j = shopArray.length; i < j; i++) {
        var shopObj = shopArray[i];
        var ratioData = stockpush.getShopSkuRatio(shopObj.shopId, data);
        seriesList[i].data = ratioData;
    }

    stockpush.skuStorageBarChart.setOption(option);

    stockpush.initRatioInputAreaByStorIndex_sku(0, $modal); // 显示第一个仓库的数据
};

stockpush.cleanSkuBarChart = function(option) {
    option.xAxis.data.length = 0;
    option.legend.data.length = 0;
    option.series.length = 0;
};

stockpush.getShopSkuRatio = function(shopId, data) {
    var returnData = [];
    var storageArray = stockpush.finalSkuRatio.storageArray;
    var storageRatioArray = data || stockpush.finalSkuRatio.storageRatioArray;
    for (var i = 0, j = storageArray.length; i < j; i++) {
        var storage = storageArray[i];

        if (!!storageRatioArray[storage.storId] && !!storageRatioArray[storage.storId][shopId]) {
            returnData[i] = storageRatioArray[storage.storId][shopId];
        } else {
            if (!!stockpush.finalSkuRatio.storageRatioArray[storage.storId]) {
                returnData[i] = stockpush.finalSkuRatio.storageRatioArray[storage.storId][shopId];
            }
        }
    }
    return returnData;
};

// 初始化图表的纵轴数据
stockpush.initSkuBarChartYSeries = function(shopArray, option) {
    for (var i = 0, j = shopArray.length; i < j; i++) {
        var shopObj = shopArray[i];
        var ratioData = stockpush.getShopSkuRatio(shopObj.shopId);

        var itemValue = {
            name : shopObj.shopName,
            type : 'bar',
            stack : '百分比',
            label : {
                normal : {
                    show : true,
                    position : 'insideRight'
                }
            },
            data : ratioData,
            markLine : {
                lineStyle : {
                    emphasis : {
                        color : "#e74c3c",
                        type : "solid"
                    }
                },
                silent : true,
                data : [ {
                    yAxis : '100'
                } ]
            }
        };

        // 1. 初始化图例
        option.legend.data.push(shopObj.shopName);
        // 2. 初始化图表数据
        option.series.push(itemValue);
    }
    stockpush.skuStorageBarChart.setOption(option);
};

// 初始化商品推送页面的input控件区域
stockpush.initSkuShopInputContainer = function(shopArray) {
    $("#shopInputContainer4Sku").empty().hide();
    var rowLength = 2;
    var tempHtml = "";
    for (var i = 0, j = shopArray.length; i < j; i++) {
        var shopObj = shopArray[i];
        if (i % rowLength == 0) {
            // 一行开始，添加行开始
            tempHtml = "<div class='row' style='margin-bottom:3px;'>";
        }

        // 获取仓库店铺比例，并添加input控件
        var storageRatio = stockpush.getShopSkuRatio(shopObj.shopId);
        var inputDisabled = "disabled";
        if ($.inArray(shopObj.shopId, stockpush.finalSkuRatio.availableShopArray) != -1) {
            inputDisabled = "";
        }
        tempHtml += "<div class='col-sm-3 text-right cut'><label class='control-label'>" + shopObj.shopName
                + "</label></div><div class='col-sm-2'><div class='input-icon right'><i data-container='body' class='tooltips'>%</i>      <input " + inputDisabled + " class='form-control text-right' type='text' id="
                + shopObj.shopId + " placeholder='%' name='" + i + "'/>   </div>     </div>";

        // 一行开始结尾或者控件列表结尾，添加行结尾
        if (i % rowLength == (rowLength - 1) || i == j - 1) {
            tempHtml += "</div>";
            $("#shopInputContainer4Sku").append($(tempHtml));
        }
    }

    // 设置店铺推送比例输入框的change事件，使修改比例后图表联动
    $("#shopInputContainer4Sku").find("input[type='text']").inputmask({
    	mask : "999",
        greedy : false,
        placeholder : '',
//        regex : "^(\\d|[1-9]\\d|100)$"
    }).bind("change", function() {
        stockpush.skuStorageBarChart.hasChanged = true;
        var index = $(this).attr("name");
        var value = $(this).val();
        var option = stockpush.skuStorageBarChart.getOption();
        var storageIndex = $("#storageName4Sku", $modal).val();

        option.series[index].data[storageIndex] = value;
        stockpush.skuStorageBarChart.setOption(option);
    });
    $("#shopInputContainer4Sku").find("input[type='text']").keyup(function(){
    	var tem = $(this).val();
    	if(parseInt(tem)>100){
    		var str = tem.substr(0,tem.length-1);
    		$(this).val("100");
    		$(this).change();
    	}
    })

    $("#shopInputContainer4Sku").show();
};

/*
 * 初始化商品推送比例设置页面的内容
 */
stockpush.initRatioSkuPage = function(option) {
    var data = stockpush.finalSkuRatio;

    // 清空图表的内容
    stockpush.cleanSkuBarChart(option);

    // 根据仓库推送比例设置图表
    if (!data.storageArray || data.storageArray.length == 0) {
        // 如果仓库数据不存在，则给出提示
        window.top.window.showScoMessage('error', "该项目下的店铺没有仓库");
    } else if (!data.shopArray || data.shopArray.length == 0) {
        window.top.window.showScoMessage('error', "该项目下没有店铺");
    } else {
        // 为option设置横坐标为仓库列表
        for (var i = 0, j = data.storageArray.length; i < j; i++) {
            option.xAxis.data.push(data.storageArray[i].name);
        }
        // 为option设置店铺图例为店铺列表
        stockpush.initSkuBarChartYSeries(data.shopArray, option);

        // 显示店铺列表的比例数据，每行2条
        stockpush.initSkuShopInputContainer(data.shopArray);

        // 设置显示区域为第一个仓库的显示内容
        stockpush.initRatioInputAreaByStorIndex_sku(0);
        
        // 显示弹出框
        showModalDialog(stockpush.operation.SKU_RATIO_SET);
    }

};

stockpush.saveSkuRatio = function() {
    if (stockpush.isExtend100(stockpush.skuStorageBarChart.getOption())) {
        window.top.window.showModalConfirm("有比例超100%，是否继续", function(event) {
            stockpush.saveSkuRatioData();
        });
    } else {
        stockpush.saveSkuRatioData();
    }
}

// 保存商品推送比例
stockpush.saveSkuRatioData = function() {
    var skuData = [];
    $("#goodsSkuTable", $modal).find("tr.selected").each(function(index, element) {
        var currentRow = stockpush.goodsSkuTable.row($(element));
        var rowData = currentRow.data();
        skuData.push(rowData);
    });

    // 父窗体归还本页的编辑对话框

    // 1. 从图表中获取数据
    var dataArray = stockpush.skuStorageBarChart.getOption().series;
    // 循环中用到的临时变量 开始
    var currentData = {};
    var currentShop = {};
    var currentStorageData = 0;
    var currentStorage = {};
    // 循环中用到的临时变量 结束

    // 2. 构造数据格式
    var params = [];

    for (var i = 0, j = dataArray.length; i < j; i++) {
        currentData = dataArray[i];
        currentShop = stockpush.finalSkuRatio.shopArray[i];
        // 如果当前店铺在可设置店铺列表中，才读取各个仓库的比例数据
        if ($.inArray(currentShop.shopId, stockpush.finalSkuRatio.availableShopArray) != -1) {
            for (var u = 0, v = currentData.data.length; u < v; u++) {
                currentStorageData = currentData.data[u];
                currentStorage = stockpush.finalSkuRatio.storageArray[u];

                var _tempData = {};
                _tempData.fmlaId = ""; // 库存公式与推送比例不直接关联
                _tempData.prjId = currentShop.prjId;
                _tempData.prjName = currentShop.prjName;
                _tempData.shopId = currentShop.shopId;
                _tempData.shopName = currentShop.shopName;
                _tempData.storId = currentStorage.storId;
                _tempData.storName = currentStorage.storName;
                _tempData.ratio = currentStorageData;
                _tempData.isUpdate = 'y';
                params.push(_tempData);
            }
        }
    }

    var skuRatioList = [];
    var tempParam = {};
    var tempSkuData = {};
    var compareValue = 0;

    for (var i = 0, j = params.length; i < j; i++) {
        tempParam = params[i];
        for (var u = 0, v = skuData.length; u < v; u++) {
            tempSkuData = skuData[u];
            var tempSkuRatio = {};
            tempSkuRatio.ratioId = "";
            tempSkuRatio.fmlaId = ""; // 库存公式与推送比例不直接关联
            tempSkuRatio.prjId = tempParam.prjId;
            tempSkuRatio.prjName = tempParam.prjName;
            tempSkuRatio.shopId = tempParam.shopId;
            tempSkuRatio.shopName = tempParam.shopName;
            tempSkuRatio.storId = tempParam.storId;
            tempSkuRatio.storName = tempParam.storName;
            tempSkuRatio.ratio = tempParam.ratio || 0;
            tempSkuRatio.goodsId = tempSkuData.goodsId;
            tempSkuRatio.goodsCode = tempSkuData.goodsCode;
            tempSkuRatio.goodsName = tempSkuData.goodsName;
            tempSkuRatio.skuCode = tempSkuData.skuCode;
            tempSkuRatio.skuName = tempSkuData.skuName;
            tempSkuRatio.skuId = tempSkuData.skuId;
            if (!!stockpush.finalSkuRatio4Single[tempSkuData.skuId] && !!stockpush.finalSkuRatio4Single[tempSkuData.skuId][tempParam.storId]) {
                compareValue = stockpush.finalSkuRatio4Single[tempSkuData.skuId][tempParam.storId][tempParam.shopId] || 0;
                if (!!compareValue && compareValue != tempSkuRatio.ratio) {
                    tempSkuRatio.isUpdate = 'y';
                    skuRatioList.push(tempSkuRatio);
                } else if (!compareValue && !!tempSkuRatio.ratio) {
                }
            } else {
                tempSkuRatio.isUpdate = 'n';
                skuRatioList.push(tempSkuRatio);
            }
        }
    }
    // 3. 保存数据
    $.ajax({
        type : "POST",
        url : "/stockPush/saveSkuRatio.action",
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        data : JSON.stringify(skuRatioList),
        async : false, // 同步加载表格数据
        success : function(data) {
            // 提示更新成功，并刷新表格
            window.top.window.showScoMessage('ok', '已经为' + skuData.length + '件选中商品更新了推送比例');
            stockpush.skuStorageBarChart.hasChanged = false;
            stockpush.reloadGoodsSkuTable();
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
    // 根据仓库Index获取设置比例数据

};

// 查询商品表格数据
stockpush.reloadGoodsSkuTable = function() {
    $("#SkuName", $modal).text("仓库推送比例");
    var optionData = stockpush.goodsSkuTable.settings()[0].ajax.data;
    optionData.quickSearch = encodeURI($("#quickSearch", $modal).val() || "");
    optionData.isSet = $("#isSet", $modal).val();
    stockpush.goodsSkuTable.settings()[0].ajax.data = optionData;
    stockpush.goodsSkuTable.ajax.reload();
};

// -------------------------商品推送比例--结束--------------------

// 公共方法
stockpush.getShopStoreRelation = function(storeId, Array) {
    var shopIdList = [];
    for (var i = 0, j = Array.length; i < j; i++) {
        var item = Array[i];
        if (item.storId == storeId) {
            shopIdList.push(item.shopId);
        }
    }
    return shopIdList;
};

// 监测是否数据大于100%，如果是，返回true；如果不是，返回false
stockpush.isExtend100 = function(option) {
    var data = option.series;
    var returnBoolean = false;
    var dataCount = data[0].data.length;
    for (var i = 0; i < dataCount; i++) {
        var count = 0;
        for (var u = 0, v = data.length; u < v; u++) {
            if(!isNaN(data[u].data[i])){
                count += Number(data[u].data[i]);
            }
        }
        
        if (count > 100) {
            returnBoolean = true;
            break;
        }
    }
    return returnBoolean;
};

function checkCorrect(string) {
    // 剔除空白符
    string = string.replace(/\s/g, '');

    // 错误情况，空字符串
    if ("" === string) {
        return false;
    }

    // 错误情况，运算符连续
    if (/[\+\-\*\/]{2,}/.test(string)) {
        return false;
    }

    // 空括号
    if (/\(\)/.test(string)) {
        return false;
    }

    // 错误情况，(后面是运算符
    if (/\([\+\-\*\/]/.test(string)) {
        return false;
    }

    // 错误情况，)前面是运算符
    if (/[\+\-\*\/]\)/.test(string)) {
        return false;
    }

    // 错误情况，(前面不是运算符
    if (/[^\+\-\*\/]\(/.test(string)) {
        return false;
    }

    // 错误情况，)后面不是运算符
    if (/\)[^\+\-\*\/]/.test(string)) {
        return false;
    }
    // 错误情况，运算符打头
    if (/^[\+\-\*\/]/.test(string)) {
        return false;
    }
    return true;
};